using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace MTRC.ODMS.Web.SOM.FireProtection
{
    /// <summary>
    /// Author:SongQianBo
    /// </summary>
    /// 
    public partial class FireProtectionEnquiry : BasePage_SOM
    {
        //edit by hjh 20120516 for issue 1531
        //protected int TempDataID
        //{
        //    get { return int.Parse(ViewState["TempDataID"].ToString()); }
        //    set { ViewState["TempDataID"] = value; }
        //}

        #region MenuID

        protected override string MenuID
        {
            get
            {
                return "M140301";
            }
        }

        #endregion

        #region Page Init And Load

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.ChangeLanguage += new ChangeLanguageEventHandler(SetLanguage_Click);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // add by dylan 20151030 for u275.1 
                this.grvData.PageSize = this.GridViewPageDefaultSize();
                FunctionItemSetting();

                SetLoadPage();
                SetLanguage();

                SetConditionFromPanelOpen();

                /*******************add by jack 20151202 for using session store enquiry condition satrt**********************/
                string isBack = Request.QueryString["isBack"];
                if (isBack == "1")
                {
                    //this.ddlStation.SelectedValue = Session["Common_Station"].ToString();
                    //this.ddlFireLink.SelectedValue = Session["FireProtection_FireLink"].ToString();
                    //this.ddlZoneGroup.SelectedValue = Session["FireProtection_ZoneGroup"].ToString();
                    if (Session["Common_Station"] != null && Session["Common_Station"].ToString() != "")
                    {
                        this.FindByValueAndSelect(ddlStation, Session["Common_Station"].ToString());
                        this.ddlStation_SelectedIndexChanged(null, null);
                    }
                    if (Session["FireProtection_FireLink"] != null && Session["FireProtection_FireLink"].ToString() != "")
                    {
                        this.FindByValueAndSelect(ddlFireLink, Session["FireProtection_FireLink"].ToString());
                        this.ddlFireLink_SelectedIndexChanged(null, null);
                    }
                    if (Session["FireProtection_ZoneGroup"] != null && Session["FireProtection_ZoneGroup"].ToString() != "")
                    {
                        this.FindByValueAndSelect(ddlZoneGroup, Session["FireProtection_ZoneGroup"].ToString());
                    }
                    this.dtbFrom.Text = Session["Common_DateFrom"].ToString();
                    this.dtbTo.Text = Session["Common_DateTo"].ToString();
                    this.SetCheckboxListValue(Session["Common_ShowList"].ToString(), this.cblShow);
                    this.ddlReason.SelectedValue = Session["FireProtection_Reason"].ToString();
                    this.SetCheckboxListValue(Session["FireProtection_Status"].ToString(), this.cblFinkStatus);
                }
                /*******************add by jack 20151202 for using session store enquiry condition end**********************/
            }
        }

        #region Req13.5 Add by Gordon 20150626

        /// <summary>
        /// SetConditionFromPanelOpen
        /// </summary>
        private void SetConditionFromPanelOpen()
        {
            string fireLinkId = Request.QueryString["FireLinkID"];
            string locationId = Request.QueryString["LocationId"];
            if (!string.IsNullOrEmpty(fireLinkId))
            {
                if (!string.IsNullOrEmpty(locationId))
                {
                    if (DAL.Security.User.CanFunctionItemAccess("M140301_F1", this.ODMUser.UserProfileID, this.MenuID) ||
                        DAL.Security.User.CanFunctionItemAccess("M140301_F2", this.ODMUser.UserProfileID, this.MenuID)
                        )
                    {
                        SelectValueForSF(locationId, fireLinkId);
                    }
                    else
                    {
                        if (this.ODMUser.LocationID == int.Parse(locationId))
                        {
                            SelectValueForSF(locationId, fireLinkId);
                        }
                        else
                        {
                            ddlStation.Items.Insert(0, new ListItem("", "-1"));
                            this.ddlStation.SelectedIndex = 0;
                            ddlFireLink.Items.Insert(0, new ListItem("", "-1"));
                            this.ddlFireLink.SelectedIndex = 0;
                            this.ddlFireLink.Enabled = false;
                            this.ddlStation.Enabled = false;
                        }
                    }
                }
            }
            //added by Nathan 2015-08-15
            if (Request.QueryString["isBack"] != null && Request.QueryString["isBack"].Trim() != string.Empty && Convert.ToInt32(Request.QueryString["isBack"].ToString()) > 0)
            { }
            else
            {
                //udpate by gordon 20151023 U261
                //btnSearch_Click(null, null);
                if (!string.IsNullOrEmpty(fireLinkId))
                {
                    if (!string.IsNullOrEmpty(locationId))
                    {
                        BindData(false, false);
                    }
                }
            }
        }

        /// <summary>
        /// Select Station & FireLink value If Can
        /// </summary>
        /// <param name="locationId">locationId</param>
        /// <param name="fireLinkId">fireLinkId</param>
        private void SelectValueForSF(string locationId, string fireLinkId)
        {
            if (ddlStation.Items.FindByValue(locationId) != null)
            {
                this.ddlStation.SelectedValue = locationId;
                BindFireLinkForChange();

                if (ddlFireLink.Items.FindByValue(fireLinkId) != null)
                {
                    this.ddlFireLink.SelectedValue = fireLinkId;
                }
                else
                {
                    ddlFireLink.Items.Insert(0, new ListItem("", "-1"));
                    this.ddlFireLink.SelectedIndex = 0;
                    this.ddlFireLink.Enabled = false;
                }
            }
            else
            {
                ddlStation.Items.Insert(0, new ListItem("", "-1"));
                this.ddlStation.SelectedIndex = 0;
                ddlFireLink.Items.Insert(0, new ListItem("", "-1"));
                this.ddlFireLink.SelectedIndex = 0;
                this.ddlFireLink.Enabled = false;
                this.ddlStation.Enabled = false;
            }
        }

        #endregion

        #endregion

        #region SetLanguage

        void SetLanguage_Click(object sender, EventArgs e)
        {
            if (IsPostBack) //added by huangyao 20090120
            {
                FunctionItemSetting();
                SetLoadPage();
            }
            SetLanguage();
        }

        private void SetLanguage()
        {
            this.lblFrom.Text = this.GetLabel("COM_From", true);
            this.lblTo.Text = this.GetLabel("COM_To", true);
            this.lblStation.Text = this.GetLabel("SOM_Station", true);
            this.lblDisplay.Text = this.GetLabel("COM_Show", true);
            this.lblReason.Text = this.GetLabel("SOM_Reason", true);
            this.lblZoneGroup.Text = this.GetLabel("SOM_ZoneGroupLoop", true);
            this.lblFrieLinkStatus.Text = this.GetLabel("SOM_FireLinkStatus", true);
            this.lblFireLink.Text = this.GetLabel("SOM_FireLink", true);
            this.lblDisplay.Text = this.GetLabel("COM_Show", true);
            this.btnSearch.Text = this.GetLabel("COM_Search");
            this.btnExport.Text = this.GetLabel("COM_Export");
            this.btnNew.Text = this.GetLabel("SOM_AddNewAssetLoanItem");

            //this.grvData.Columns[6].HeaderText = this.GetLabel("COM_Status") + "/" + "<BR />" + this.GetLabel("SOM_HighLight");

            BindReason();
            BindFireLink();
            BindFireZoneGroup();

            if ((this.Request["FireZoneGrpID"] != null && this.Request["FireLinkID"] != null) || this.Request["StationEventIDs"] != null)
            {
                BindEventStatusCheckBox(true);
            }
            else
            {
                BindEventStatusCheckBox(false);
            }

            BindFireStatusCheckBox();

            //add by gordon 20150923
            string fireLinkId = Request.QueryString["FireLinkID"];
            string locationId = Request.QueryString["LocationId"];
            if ((!string.IsNullOrEmpty(fireLinkId)) && (!string.IsNullOrEmpty(locationId)))
            {
                return;
            }
            //add end....

            if (this.Request["FireZoneGrpID"] != null && this.Request["FireLinkID"] != null)
            {
                BindData(true, false);
            }
            else if (this.Request["StationEventIDs"] != null)
            {
                BindData(false, true);
            }
            else
            {
                //added by Nathan 2015-08-15
                if (Request.QueryString["isBack"] != null && Request.QueryString["isBack"].Trim() != string.Empty && Convert.ToInt32(Request.QueryString["isBack"].ToString()) > 0)
                { }
                else
                {
                    BindData(false, false);
                }
            }

        }

        #endregion

        #region Event

        protected void btnNew_Click(object sender, EventArgs e)
        {
            this.Response.Redirect("FireProtectionEntry.aspx?Action=New");
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                //remove by gordon 20151023 U261
                ////add by gordon 20150923
                //string fireLinkId = Request.QueryString["FireLinkID"];
                //string locationId = Request.QueryString["LocationId"];
                //if (sender == null)
                //{
                //    if (string.IsNullOrEmpty(fireLinkId) && string.IsNullOrEmpty(locationId))
                //    {
                //        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", "showWait('');", true);
                //        return;
                //    }
                //}
                ////add end....

                if (CheckFromToDate() == false)
                {
                    this.PAlert(this.GetMessage("COM_StartEndDate"));
                    return;
                }
                BindData(false, false);
            }
            finally
            {
                //add by gordon 20150812 | For Search Wait Cursor
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", "showWait('');", true);
            }
        }

        protected void grvData_NeedDataBind()
        {
            BindData(false, false);
        }


        protected void btnExport_Click(object sender, EventArgs e)
        {
            //edit by hjh 20120516 for issue 1531
            //string fileName = "";
            //fileName = MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime().ToString() + System.Guid.NewGuid().ToString();
            if (CheckFromToDate() == false)
            {
                this.Alert(this.GetMessage("COM_StartEndDate"));
                return;
            }
            DataSet dsReturn = new DataSet();
            //if (MTRC.ODMS.BLL.SOM.TempData.GetCacheData(TempDataID) != null)
            //{
            //    dsReturn = MTRC.ODMS.BLL.SOM.TempData.GetCacheData(TempDataID);
            //}
            dsReturn = this.getData(false, false).DataSet;
            object limitExpCount = DAL.CommonData.GetNumVal("SOM_FireProtectionExportMAXControl");
            if (dsReturn == null)
            {
                /********edit by jack 20151130 for u253 Processing application errors and exceptions start****/
                //return;
                string errorMessage = string.Format(GetMessage("SOM_AdmissionRegistryEnquiryException", this.LangCode), GetLineNum());
                /********edit by jack 20151130 for u253 Processing application errors and exceptions end****/
                Application_Error(errorMessage, "AdmissionRegistryEnquiry.aspx.cs");
            }
            else if (limitExpCount != null && dsReturn.Tables[0].Rows.Count > int.Parse(limitExpCount.ToString()))//edit by hjh 20120516 for issue 1531
            {
                Alert(string.Format(this.GetMessage("SOM_ExportLimitControl"), int.Parse(limitExpCount.ToString())));
                return;
            }

            DataTable dtSearchResult = dsReturn.Tables[0];
            dtSearchResult.Columns.Remove("StationEventID");
            dtSearchResult.Columns.Remove("EventStatusID");
            dtSearchResult.Columns.Remove("FireLinkStatusID");
            dtSearchResult.Columns.Remove("IsolateReasonID");
            //dtSearchResult.Columns.Remove("FlagHandover");
            dtSearchResult.Columns.Remove("HandoverNote");
            dtSearchResult.Columns.Remove("ParentStationEventID");
            /******************* add by dylan 20150728 for u133 start**********************************/
            //dtSearchResult.Columns[0].ColumnName = this.GetLabel("SOM_EventNo");
            //dtSearchResult.Columns[1].ColumnName = this.GetLabel("COM_IsolationTime");
            //dtSearchResult.Columns[2].ColumnName = this.GetLabel("SOM_CompleteTime");
            //dtSearchResult.Columns[3].ColumnName = this.GetLabel("SOM_FireLink");

            //dtSearchResult.Columns[4].ColumnName = this.GetLabel("SOM_Reason");
            //dtSearchResult.Columns[5].ColumnName = this.GetLabel("SOM_FireLinkStatus");

            //dtSearchResult.Columns[6].ColumnName = this.GetLabel("SOM_LoopBeingIsolated");
            //dtSearchResult.Columns[7].ColumnName = this.GetLabel("COM_Status");
            //dtSearchResult.Columns[8].ColumnName = this.GetLabel("SOM_Handover");
            //dtSearchResult.Columns[9].ColumnName = this.GetLabel("SOM_HighLight");
            for (int i = 0; i < dtSearchResult.Rows.Count; i++)
            {
                if (dtSearchResult.Rows[i]["HighLight"].ToString() == "1")
                {
                    dtSearchResult.Rows[i]["HighLightDesc"] = base.GetLabel("SOM_HighLightYellow");
                }
                else if (dtSearchResult.Rows[i]["HighLight"].ToString() == "2")
                {
                    dtSearchResult.Rows[i]["HighLightDesc"] = base.GetLabel("SOM_HighLightRed");
                }
                else
                {
                    dtSearchResult.Rows[i]["HighLightDesc"] = base.GetLabel("SOM_HighLightNormal");
                }
            }
            dtSearchResult.Columns.Remove("HighLight");
            dtSearchResult.Columns["StaffName"].SetOrdinal(4);
            dtSearchResult.Columns["Company"].SetOrdinal(5);
            dtSearchResult.Columns["EventNo"].ColumnName = this.GetLabel("SOM_EventNo");
            dtSearchResult.Columns["EventTime"].ColumnName = this.GetLabel("COM_IsolationTime");
            dtSearchResult.Columns["EventCompleteTime"].ColumnName = this.GetLabel("SOM_CompleteTime");
            dtSearchResult.Columns["FireLinkCode"].ColumnName = this.GetLabel("SOM_FireLink");
            dtSearchResult.Columns["StaffName"].ColumnName = this.GetLabel("SOM_RequestbyName");
            dtSearchResult.Columns["Company"].ColumnName = this.GetLabel("SOM_RequestbyOUCompany");
            dtSearchResult.Columns["IsolateReasonCode"].ColumnName = this.GetLabel("SOM_Reason");
            dtSearchResult.Columns["FireLinkStatusCode"].ColumnName = this.GetLabel("SOM_FireLinkStatus");
            dtSearchResult.Columns["OOSGroupCode"].ColumnName = this.GetLabel("SOM_LoopBeingIsolated");
            dtSearchResult.Columns["EventStatusDesc"].ColumnName = this.GetLabel("COM_Status");
            dtSearchResult.Columns["FlagHandover"].ColumnName = this.GetLabel("SOM_Handover");
            dtSearchResult.Columns["HighLightDesc"].ColumnName = this.GetLabel("SOM_HighLight");
            dtSearchResult.Columns["CHUBB"].ColumnName = this.GetLabel("SOM_CHUBB");
            dtSearchResult.Columns["Handledby"].ColumnName = this.GetLabel("SOM_Handledby");
            dtSearchResult.Columns["RestoreCHUBB"].ColumnName = this.GetLabel("SOM_RestoreCHUBB");
            dtSearchResult.Columns["RestorehandledBy"].ColumnName = this.GetLabel("SOM_RestorehandledBy");
            dtSearchResult.Columns["Remark"].ColumnName = this.GetLabel("COM_Remark");

            //Common.ExportExcel_showHHMM(dsReturn, Context, "Fire Protection.xls");
            //string templateFile = Server.MapPath("~") + string.Format(@"\Template\MTRC\Fire ProtectionTemplate.xlsx");
            string templateFilePath = APJ.Util.Utility.GetAppSetting("SOM_ExportExcelTemplatePath");
            if (templateFilePath.LastIndexOf("\\") != templateFilePath.Length - 1)
                templateFilePath += "\\";
            string templateFile = templateFilePath + string.Format("Fire ProtectionTemplate.xlsx");//add by jack 20160127 ISU22 fixed for same export file name
            //string exportFile = Server.MapPath("~") + string.Format(@"\Template\MTRC\Fire Protection.xlsx");
            string ExcelDownloadFilePath = APJ.Util.Utility.GetAppSetting("SOM_ExportExcelTempFilePath");
            if (ExcelDownloadFilePath.LastIndexOf("\\") != ExcelDownloadFilePath.Length - 1)
                ExcelDownloadFilePath += "\\";
            string exportFile = ExcelDownloadFilePath + string.Format("Fire Protection" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");//add by jack 20160127 ISU22 fixed for same export file name
            //update by gordon 20150910
            //CreateExcelFile.ExportExcelWithTemplate(dtSearchResult, templateFile, exportFile, Response);
            CreateExcelFile.ExportExcelWithTemplate(dtSearchResult, templateFile, exportFile, Response, Page);
            /******************* add by dylan 20150723 for u133 end**********************************/
            dtSearchResult.Dispose();
            dsReturn.Dispose();
            dtSearchResult = null;
            dsReturn = null;

        }
        #endregion

        #region define funtion
        private void BindData(bool loadFromFireZoneGroupStatus, bool loadFromFireLinkEntry)
        {
            /* Comment by jack 20150822 for u70 */
            if (DAL.Security.User.CanFunctionItemAccess("M140301_F1", this.ODMUser.UserProfileID, this.MenuID))//access all station.
            {

            }
            else if (DAL.Security.User.CanFunctionItemAccess("M140301_F2", this.ODMUser.UserProfileID, this.MenuID))//Can Access other stations.
            {

            }
            else
            {
                if (!IsValidStation(this.ODMUser.LocationID))
                {
                    if (Request.QueryString["IsReject"] != "1")
                    {
                        this.PAlert(this.GetMessage("SOM_NotValidStation"));
                    }
                    this.ddlStation.Items.Clear();
                    DataTable dtNull = new DataTable();
                    this.grvData.DataSource = dtNull.DefaultView;
                    this.grvData.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
                    this.grvData.DataBind();
                    dtNull.Dispose();
                    return;
                }

            }
            /************************************/

            //edit by hjh 20120516 for issue 1531
            DataTable dt = new DataTable();
            dt = this.getData(loadFromFireZoneGroupStatus, loadFromFireLinkEntry);
            //TempDataID = MTRC.ODMS.BLL.SOM.TempData.CacheDataSet(dt.DataSet, this.ODMUser.ID, this.ODMUser.Domain);
            this.grvData.DataSource = dt.DefaultView;
            this.grvData.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
            this.grvData.DataBind();

            //Set Export button enabled
            if (dt.Rows.Count <= 0)
            {
                this.btnExport.Enabled = false;
            }
            else
            {
                this.btnExport.Enabled = true;
            }

            dt.Dispose();
            dt = null;
        }

        /// <summary>
        /// Bind Status Chekct Box and add a Handover check box
        /// </summary>
        private void BindEventStatusCheckBox(bool selectAll)
        {
            this.cblShow.DataSource = DAL.SOM.CodeSetup.CDEventStatus.GetActive(this.LangCode).DefaultView;
            this.cblShow.DataValueField = "EventStatusID";
            this.cblShow.DataTextField = "Description";
            this.cblShow.DataBind();
            this.cblShow.Items.Insert(2, this.GetLabel("SOM_Handover"));
            if (selectAll == true)
            {
                for (int i = 0; i <= this.cblShow.Items.Count - 1; i++)
                {
                    this.cblShow.Items[i].Selected = true;
                }
            }
            else
            {
                this.cblShow.Items[1].Selected = true;
                this.cblShow.Items[2].Selected = true;
            }
        }

        //huangyao 20081223------------------------------
        //private void BindFireStatusCheckBox()
        //{
        //    this.cblFinkStatus.DataSource = DAL.SOM.CodeSetup.CDFireLinkStatus.GetAllFireLinkStatus(this.LangCode);
        //    this.cblFinkStatus.DataValueField = "FireLinkStatusID";
        //    this.cblFinkStatus.DataTextField = "FireLinkStatusCode";

        //    this.cblFinkStatus.DataBind();

        //    for (int i=0; i<=this.cblFinkStatus.Items.Count - 1; i++)
        //    {
        //        this.cblFinkStatus.Items[i].Selected = true;
        //    }
        //}
        //------------------------------

        //huangyao 20081223-------------------------------
        //Bind fire link status.
        private void BindFireStatusCheckBox()
        {
            BindListControl(this.cblFinkStatus, "FireLinkStatusID", "FireLinkStatusCode", DAL.SOM.CodeSetup.CDFireLinkStatus.GetAllFireLinkStatus(this.LangCode), false);

            //------------------------------- Modify by zengshunbo 2009-06-12 --------------------------
            //----Del:
            ////Remove VRT if current version=BJL4.
            //if (this.Version == MTRC.ODMS.BLL.EnvVersion.BJL4 && cblFinkStatus.Items.FindByValue("3") != null)
            //{
            //    cblFinkStatus.Items.Remove(cblFinkStatus.Items.FindByValue("3"));
            //}

            //----Add:
            if (DAL.CommonData.GetCharVal("MV_SOM_FireProtectionEnquiryVRT_Visible").ToUpper() == "N" && cblFinkStatus.Items.FindByValue("3") != null)
            {
                cblFinkStatus.Items.Remove(cblFinkStatus.Items.FindByValue("3"));
            }

            //------------------------------- End modify by zengshunbo 2009-06-12 ----------------------

            for (int i = 0; i <= this.cblFinkStatus.Items.Count - 1; i++)
            {
                this.cblFinkStatus.Items[i].Selected = true;
            }
        }
        //-----------------------------------

        /// <summary>
        /// setting user access by function item.
        /// </summary>
        /// 

        private void FunctionItemSetting()
        {
            if (DAL.Security.User.CanFunctionItemAccess("M140301_F1", this.ODMUser.UserProfileID, this.MenuID))//access all station.
            {
                //update by gordon 20151020 U247
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.StationID), true);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.LocationID), true);
            }
            else if (DAL.Security.User.CanFunctionItemAccess("M140301_F2", this.ODMUser.UserProfileID, this.MenuID))//Can Access other stations.
            {
                //BindStation
                //update by gordon 20151020 U247
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID), true);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), true);
            }
            else
            {
                //Update By Gordon 20150626 Req13.5
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID), true);
                //update by gordon 20151020 U247
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID), false);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), false);
                this.ddlStation.Enabled = false;
            }

            //this.ddlStation.Items.Insert(0, this.LiALL());

            if (DAL.Security.User.CanFunctionItemAccess("M140701_F3", this.ODMUser.UserProfileID, this.MenuID)) //readonly
            {
                this.btnNew.Enabled = false;
            }

            //update by gordon 20151020 U247
            //if (ddlStation.Items.FindByValue(this.ODMUser.StationID.ToString()) != null)
            //{
            //    this.ddlStation.SelectedValue = this.ODMUser.StationID.ToString();
            //}
            if (ddlStation.Items.FindByValue(this.ODMUser.LocationID.ToString()) != null)
            {
                this.ddlStation.SelectedValue = this.ODMUser.LocationID.ToString();
            }
        }

        /// <summary>
        /// Bind drop down list reason
        /// </summary>
        private void BindReason()
        {
            DataTable dt = MTRC.ODMS.DAL.SOM.CodeSetup.CDIsolateReason.GetAllIsolateReason(this.LangCode);
            BindListControl(this.ddlReason, "IsolateReasonID", "IsolateReasonCode", dt, true);

            dt.Dispose();
            dt = null;
        }

        /// <summary>
        /// Bind drop down list FireLink
        /// </summary>
        private void BindFireLink()
        {
            string stations = "";
            //update by benson 2015-10-14  U70 begin
            //if (this.ddlStation.SelectedItem != null)
            //{
            //    if (this.ddlStation.SelectedValue == "0")
            //    {
            //        foreach (ListItem item in ddlStation.Items)
            //        {
            //            stations = stations + "," + item.Value;
            //        }
            //    }
            //    else
            //    {
            //        stations = this.ddlStation.SelectedValue;
            //    }
            //}
            SetStationSelectedItem(ref stations, this.ddlStation);
            //update by benson 2015-10-14  U70 end

            //DataTable dt = MTRC.ODMS.DAL.SOM.CodeSetup.CDFireLink.GetAllFireLink(this.LangCode);
            DataTable dt = MTRC.ODMS.BLL.SOM.Event.FireProtection.GetFireLinkByStationIDs(this.LangCode, stations);
            BindListControl(this.ddlFireLink, "FireLinkID", "FireLinkCode", dt, true);

            dt.Dispose();
            dt = null;
        }

        /// <summary>
        /// Bind drop down list Fire Zone Group
        /// </summary>
        private void BindFireZoneGroup()
        {
            string fireLinkIDs = "";
            //update by benson 2015-10-14  U70 begin
            //if (this.ddlFireLink.SelectedItem != null)
            //{
            //    if (this.ddlFireLink.SelectedValue == "0")
            //    {
            //        foreach (ListItem item in this.ddlFireLink.Items)
            //        {
            //            fireLinkIDs = fireLinkIDs + "," + item.Value;
            //        }
            //    }
            //    else
            //    {
            //        fireLinkIDs = this.ddlFireLink.SelectedValue;
            //    }
            //}
            SetStationSelectedItem(ref fireLinkIDs, this.ddlFireLink);
            //update by benson 2015-10-14  U70 end

            DataTable dt = MTRC.ODMS.DAL.SOM.CodeSetup.CDFireZoneGrp.GetFireZoneGroupByFireLinkIDs(this.LangCode, fireLinkIDs);
            BindListControl(this.ddlZoneGroup, "FireZoneGrpID", "FireZoneGrpCode", dt, true);

            dt.Dispose();
            dt = null;

            if (TextddlZoneGroup.Text.Trim().Length > 0)
            {
                string subStr = TextddlZoneGroup.Text;
                ddlZoneGroup.SelectedItem.Text = subStr;
                TextddlZoneGroup.Text = "";
            }

        }

        private void SetLoadPage()
        {
            this.btnExport.Enabled = false;

            int days = int.Parse(MTRC.ODMS.DAL.CommonData.GetNumVal("SOM_FireProtectionEnquiryDateRange").ToString());
            if (this.Request["FireZoneGrpID"] != null && this.Request["FireLinkID"] != null)
            {
                this.dtbFrom.SetDateTime(DateTime.MinValue);
                this.dtbTo.SetDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime());
            }
            else
            {
                // edit by dylan 20150902 for u189 issue log
                this.dtbFrom.SetDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime().Date.AddDays(-days));
                this.dtbTo.SetDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime().Date);
            }

            if (this.Request["StationEventIDs"] != null)
            {
                this.dtbFrom.SetDateTime(DateTime.MinValue);
                this.dtbTo.SetDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime());

            }

            if (DAL.Security.User.CanFunctionItemAccess("M140301_F3", this.ODMUser.UserProfileID, this.MenuID))//access all station.
            {
                this.btnNew.Enabled = false;
            }
        }

        /// <summary>
        /// Check From Date and To Date
        /// </summary>
        /// 

        private bool CheckFromToDate()
        {
            if (this.dtbFrom.GetDateTime() != DateTime.MinValue && this.dtbTo.GetDateTime() != DateTime.MinValue)
            {
                if (InvalidateInputDate(this.dtbFrom.GetDateTime(), this.dtbTo.GetDateTime()))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// Bind fire link.
        /// </summary>
        private void BindFireLinkForChange()
        {
            int stationID = 0;

            if (this.ddlStation.SelectedItem != null)
            {
                stationID = Convert.ToInt32(ddlStation.SelectedItem.Value);
            }

            DataTable dt = ODMS.DAL.SOM.CodeSetup.CDFireLink.GetFirelinkCode(this.LangCode, stationID);
            BindListControl(this.ddlFireLink, "FirelinkID", "FireLinkCode", dt, true);
        }

        private void BindFireZoneGroupForChange()
        {
            DataTable dtZoneGroup = MTRC.ODMS.DAL.SOM.Event.StationEventFireZoneGroupDa.GetFireZoneGroupFormCDTable(Convert.ToInt32(this.ddlFireLink.SelectedValue.ToString()));
            BindListControl(this.ddlZoneGroup, "FireZoneGrpID", "FireZoneGrpCode", dtZoneGroup, true);
        }

        #endregion

        protected void grvData_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //set Event Status icons
                if (((Label)e.Row.Cells[6].FindControl("lblStatusID")).Text == "1")
                {
                    ((Image)e.Row.Cells[6].FindControl("imgStatus")).ImageUrl = "../../Images/SOM/EventStatus_OS.gif";
                    ((Image)e.Row.Cells[6].FindControl("imgStatus")).ToolTip = this.GetLabel("SOM_OS");
                }
                else if (((Label)e.Row.Cells[6].FindControl("lblStatusID")).Text == "2")
                {
                    ((Image)e.Row.Cells[6].FindControl("imgStatus")).ImageUrl = "../../Images/SOM/EventStatus_COM.gif";
                    ((Image)e.Row.Cells[6].FindControl("imgStatus")).ToolTip = this.GetLabel("SOM_Completed");
                }
                else if (((Label)e.Row.Cells[6].FindControl("lblStatusID")).Text == "3")
                {
                    ((Image)e.Row.Cells[6].FindControl("imgStatus")).ImageUrl = "../../Images/SOM/EventStatus_Void.gif";
                    ((Image)e.Row.Cells[6].FindControl("imgStatus")).ToolTip = this.GetLabel("SOM_Voided");
                }

                //Set hand over icons
                if (((Label)e.Row.Cells[7].FindControl("lblHandOver")).Text == "True")
                {
                    ((Image)e.Row.Cells[7].FindControl("imgHandOver")).ImageUrl = "../../Images/SOM/EventHandOver.gif";
                    ((Image)e.Row.Cells[7].FindControl("imgHandOver")).ToolTip = ((Label)e.Row.Cells[7].FindControl("lblHandoverNote")).Text;

                }
                else
                {
                    // edit by dylan 20150820 for u81.1
                    string HandOverNote = ((Label)e.Row.Cells[7].FindControl("lblHandoverNote")).Text;
                    if (!string.IsNullOrEmpty(HandOverNote))
                    {
                        ((Image)e.Row.Cells[7].FindControl("imgHandOver")).ImageUrl = Request.ApplicationPath + "/Images/SOM/EventHandOverDone.jpg";
                        ((Image)e.Row.Cells[7].FindControl("imgHandOver")).ToolTip = HandOverNote.Replace("\r\n", "");
                    }
                    else
                    {
                        ((Image)e.Row.Cells[7].FindControl("imgHandOver")).Visible = false;
                    }
                }

                //set high light icons
                //update by benson 2015.08.27 u183.3 begin
                if (((Label)e.Row.Cells[6].FindControl("lblStatusID")).Text == "2")
                {
                    ((Image)e.Row.Cells[8].FindControl("imgHighLight")).ImageUrl = "../../Images/SOM/HighLight_Normal.gif";
                    ((Image)e.Row.Cells[8].FindControl("imgHighLight")).ToolTip = this.GetLabel("SOM_HighLightNormal");
                }
                //update by benson 2015.08.27 u183.3 end
                else if (((Label)e.Row.Cells[8].FindControl("lblHighLight")).Text == "1")
                {
                    ((Image)e.Row.Cells[8].FindControl("imgHighLight")).ImageUrl = "../../Images/SOM/HighLight_Yellow.gif";
                    ((Image)e.Row.Cells[8].FindControl("imgHighLight")).ToolTip = this.GetLabel("SOM_HighLightYellow");
                }
                else if (((Label)e.Row.Cells[8].FindControl("lblHighLight")).Text == "2")
                {
                    ((Image)e.Row.Cells[8].FindControl("imgHighLight")).ImageUrl = "../../Images/SOM/HighLight_Red.gif";
                    ((Image)e.Row.Cells[8].FindControl("imgHighLight")).ToolTip = this.GetLabel("SOM_HighLightRed");
                }
                else
                {
                    ((Image)e.Row.Cells[8].FindControl("imgHighLight")).ImageUrl = "../../Images/SOM/HighLight_Normal.gif";
                    ((Image)e.Row.Cells[8].FindControl("imgHighLight")).ToolTip = this.GetLabel("SOM_HighLightNormal");
                }



                //add by SQB 2008-10-27 in action log 0477 begin
                //((HyperLink)e.Row.Cells[0].FindControl("hypLinkAdminReg")).NavigateUrl = APJ.Util.Utility.GetHttpHost(this.Request) + "/SOM/AdmissionRegistry/AdmissionRegistryEntry.aspx?StationEventID=" + this.grvData.DataKeys[e.Row.RowIndex]["StationEventID"].ToString();
                //((HyperLink)e.Row.Cells[0].FindControl("hypLinkAdminReg")).Target = "_blank";
                if (this.grvData.DataKeys[e.Row.RowIndex]["ParentStationEventID"].ToString().Trim() != "")
                {
                    ////huangyao 20081129 in MTR office
                    string urlString = APJ.Util.Utility.GetHttpHost(this.Request) + "/SOM/AdmissionRegistry/AdmissionRegistryEntry.aspx?StationEventID=" + this.grvData.DataKeys[e.Row.RowIndex]["ParentStationEventID"].ToString();
                    string strScript = "OpenEntryPageMaximum('" + urlString + "');";
                    ((HyperLink)e.Row.Cells[0].FindControl("hypLinkAdminReg")).Visible = true;
                    ((HyperLink)e.Row.Cells[0].FindControl("hypLinkAdminReg")).NavigateUrl = "";
                    ((HyperLink)e.Row.Cells[0].FindControl("hypLinkAdminReg")).Font.Bold = true;
                    ((HyperLink)e.Row.Cells[0].FindControl("hypLinkAdminReg")).Target = "_blank";
                    ((HyperLink)e.Row.Cells[0].FindControl("hypLinkAdminReg")).Attributes.Add("onclick", strScript);
                    //--------------------
                }
                else
                {
                    ((HyperLink)e.Row.Cells[0].FindControl("hypLinkAdminReg")).Visible = false;
                }
                //add by SQB 2008-10-27 in action log 0477 begin end..


                ((Label)e.Row.Cells[1].FindControl("lblgrvEventTime")).Text = this.FormatDateTime(DateTime.Parse(((Label)e.Row.Cells[1].FindControl("lblgrvEventTime")).Text), true);

                if (!String.IsNullOrEmpty(((Label)e.Row.Cells[1].FindControl("lblgrvEventCompleteTime")).Text))
                {
                    ((Label)e.Row.Cells[1].FindControl("lblgrvEventCompleteTime")).Text = this.FormatDateTime(DateTime.Parse(((Label)e.Row.Cells[1].FindControl("lblgrvEventCompleteTime")).Text), true);
                }

                ////huangyao 20081129 in MTR office
                string urlString2 = "FireProtectionEntry.aspx?Action=Edit&StationEventID=" + this.grvData.DataKeys[e.Row.RowIndex]["StationEventID"].ToString();
                string strScript2 = "OpenEntryPageMaximum('" + urlString2 + "');";
                //((Label)e.Row.Cells[0].FindControl("lblGrvEventNo")).Text = "<a target=_blank href='FireProtectionEntry.aspx?Action=Edit&StationEventID=" + this.grvData.DataKeys[e.Row.RowIndex]["StationEventID"].ToString() + "'>" + ((Label)e.Row.Cells[0].FindControl("lblGrvEventNo")).Text + "</a>";
                ((Label)e.Row.Cells[0].FindControl("lblGrvEventNo")).Text = "<a style='cursor: pointer;' target='_blank' onclick=" + strScript2 + ">" + ((Label)e.Row.Cells[0].FindControl("lblGrvEventNo")).Text + "</a>";
                //style='cursor: pointer; font-weight: bold;'  //and this is can done also
                ((Label)e.Row.Cells[0].FindControl("lblGrvEventNo")).Font.Bold = true;
                //-------------
            }
        }

        //------------------- Add by Zengshunbo 2009-01-04 (PI8002_ActionLog(2008-12-31)) -----------------------

        protected void ddlStation_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (ddlStation.SelectedIndex == 0)
            //{
            BindFireLink();
            BindFireZoneGroup();
            //}
            //else
            //{
            //BindFireLinkForChange();
            //BindFireZoneGroupForChange();
            //}
        }

        protected void ddlFireLink_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindFireZoneGroup();

            //-------------------- Set selected corresponding station -------------------
            //if (this.ddlFireLink.SelectedItem != null && this.ddlFireLink.SelectedValue != "0")
            //{
            //    string station = BLL.SOM.Event.FireProtection.GetStationIDByFireLinkID(this.LangCode, Convert.ToInt32(this.ddlFireLink.SelectedValue)).ToString();
            //    if (this.ddlStation.Items.FindByValue(station) != null)
            //    {
            //        this.ddlStation.SelectedValue = station;
            //    }
            //}
            //-------------------- End set selected corresponding station -------------------
        }

        protected void hbtnExport_ServerClick(object sender, EventArgs e)
        {
            btnExport_Click(sender, e);
        }

        //protected void ddlZoneGroup_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //-------------------- Set selected corresponding station and Firelink -------------------
        //if (this.ddlZoneGroup.SelectedItem != null && this.ddlZoneGroup.SelectedValue != "0")
        //{
        //    //this.ddlZoneGroup.SelectedItem.Value;
        //    string fireLinkID = BLL.SOM.Event.FireProtection.GetFireLinkIDByFireZoneGroupID(this.LangCode,Convert.ToInt32(this.ddlZoneGroup.SelectedValue)).ToString();

        //    if (this.ddlFireLink.Items.FindByValue(fireLinkID) != null)
        //    {
        //        this.ddlFireLink.SelectedValue = fireLinkID;
        //    }

        //    string station = BLL.SOM.Event.FireProtection.GetStationIDByFireLinkID(this.LangCode, Convert.ToInt32(fireLinkID)).ToString();
        //    if (this.ddlStation.Items.FindByValue(station) != null)
        //    {
        //        this.ddlStation.SelectedValue = station;
        //    }
        //}
        //-------------------- End set selected corresponding station and Firelink -------------------
        //}

        //------------------- End add by zengshunbo 2009-01-04 (PI8002_ActionLog(2008-12-31)) -----------------------
        //add by hjh 20120516 for issue 1531
        private DataTable getData(bool loadFromFireZoneGroupStatus, bool loadFromFireLinkEntry)
        {
            DataTable dt = new DataTable();
            string stationIDs = "";
            string fireZoneGroupCode = "";
            int fireZoneGroupID = 0;
            int fireLinkID = 0;

            if (loadFromFireZoneGroupStatus == true && this.Request["FireLinkID"] != null)
            {
                fireLinkID = int.Parse(this.Request["FireLinkID"].ToString());
                this.ddlFireLink.SelectedValue = fireLinkID.ToString();
                this.cblShow.Items[1].Selected = true;
                this.cblShow.Items[0].Selected = false;
                this.cblShow.Items[3].Selected = false;
                this.cblShow.Items[2].Selected = false;
            }
            else if (loadFromFireLinkEntry == true)
            {
                this.cblShow.Items[1].Selected = true;
                this.cblShow.Items[0].Selected = true;
                this.cblShow.Items[3].Selected = true;
                this.cblShow.Items[2].Selected = true;
            }
            else
            {
                fireLinkID = int.Parse(this.ddlFireLink.SelectedValue);
            }

            if (this.Request["FireZoneGrpID"] != null && loadFromFireZoneGroupStatus == true)
            {
                fireZoneGroupID = int.Parse(this.Request["FireZoneGrpID"].ToString());
                this.ddlZoneGroup.SelectedValue = fireZoneGroupID.ToString();
            }
            //else
            //{
            //    fireZoneGroupID = int.Parse(this.ddlZoneGroup.SelectedValue);
            //}


            SetStationSelectedItem(ref stationIDs, this.ddlStation);
            fireZoneGroupCode = this.ddlZoneGroup.SelectedItem.Text.Trim();
            fireZoneGroupID = this.ddlZoneGroup.SelectedIndex;

            if (this.hdnSearchByFireLinkID.Value == "0" && string.Concat(Request.QueryString["FireLinkID"]).Trim().Length > 0)
            {
                this.dtbFrom.SetDateTime(DateTime.MinValue);
                this.dtbTo.SetDateTime(DateTime.MinValue);
                for (int i = 0; i < this.cblFinkStatus.Items.Count; i++)
                {
                    this.cblFinkStatus.Items[i].Selected = true;
                }
                for (int i = 0; i < this.cblShow.Items.Count; i++)
                {
                    if (this.cblShow.Items[i].Value == "1")
                    {
                        this.cblShow.Items[i].Selected = true;
                    }
                    else
                    {
                        this.cblShow.Items[i].Selected = false;
                    }
                }
                //this.ddlStation.SelectedIndex = 0;//Delete By Gordon 20150626
                //update by gordon 20151023 U261
                if (string.IsNullOrEmpty(Request.QueryString["LocationId"]))
                {
                    stationIDs = "";
                }
                this.hdnSearchByFireLinkID.Value = "1";
                FindByValueAndSelect(ddlFireLink, Request.QueryString["FireLinkID"]);
                fireLinkID = int.Parse(this.ddlFireLink.SelectedValue);
            }

            //huangyao 20081213
            //this.cblFinkStatus.Items[2].Selected, //BJ version no VRT
            bool isHasNormal = this.cblFinkStatus.Items[0].Selected;
            bool isHasOOS = this.cblFinkStatus.Items[1].Selected;
            bool isHasVRT = false;
            if (cblFinkStatus.Items.FindByValue("3") != null)
            {
                isHasVRT = this.cblFinkStatus.Items[2].Selected; //BJ version
            }
            bool isHasTest = cblFinkStatus.Items.FindByValue("4").Selected; // this.cblFinkStatus.Items[3].Selected;
            //----------------------

            if (loadFromFireLinkEntry == false)
            {
                dt = MTRC.ODMS.DAL.SOM.Event.StationEventFirelinkDa.GetFireProtection(this.LangCode,
                                                                                      this.dtbFrom.GetDateTime(),
                                                                                      this.dtbTo.GetDateTime(),
                                                                                      stationIDs,
                                                                                      int.Parse(this.ddlReason.SelectedValue),
                                                                                      fireLinkID,
                                                                                      this.cblShow.Items[1].Selected,
                                                                                      this.cblShow.Items[0].Selected,
                                                                                      this.cblShow.Items[3].Selected,
                                                                                      this.cblShow.Items[2].Selected,
                                                                                      isHasNormal,
                                                                                      isHasOOS,
                    //update by gordon 20150826 U174.2
                    //isHasTest,
                                                                                      isHasVRT,
                    //-------------------------
                                                                                      isHasTest,
                                                                                      fireZoneGroupID,
                                                                                      fireZoneGroupCode,
                                                                                      this.GetLabel("SOM_HighLightNormal"),
                                                                                      this.GetLabel("SOM_HighLightRed"),
                                                                                      this.GetLabel("SOM_HighLightYellow")
                                                                                      );
            }
            else
            {
                dt = MTRC.ODMS.DAL.SOM.Event.StationEventFirelinkDa.GetFireProtectionByStationEventIDs(this.LangCode,
                                                                                                       this.Request["StationEventIDs"].ToString(),
                                                                                                       this.GetLabel("SOM_HighLightNormal"),
                                                                                                       this.GetLabel("SOM_HighLightRed"),
                                                                                                       this.GetLabel("SOM_HighLightYellow")
                                                                                                       );
            }
            return dt;
        }

        /// <summary>
        /// add by jack 20151202 for using session store enquiry condition
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSetSession_Click(object sender, EventArgs e)
        {
            this.RemoveCommonSession();

            string Url = this.HiddenFieldUrl.Value;
            Session["Common_Station"] = this.ddlStation.SelectedValue.ToString();
            Session["Common_DateFrom"] = this.dtbFrom.Text.ToString();
            Session["Common_DateTo"] = this.dtbTo.Text.ToString();
            Session["Common_ShowList"] = this.GetCheckboxListValue(this.cblShow);
            Session["FireProtection_Reason"] = this.ddlReason.SelectedValue.ToString();
            Session["FireProtection_Status"] = this.GetCheckboxListValue(this.cblFinkStatus);
            Session["FireProtection_FireLink"] = this.ddlFireLink.SelectedValue.ToString();
            Session["FireProtection_ZoneGroup"] = this.ddlZoneGroup.SelectedValue.ToString();

            Response.Redirect(Url + "&isBack=1&PageID=FireProtectionEnquiry");
        }
    }
}
